package com.wly.data
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;

	public class XmlBatchLoader
	{
		private var _urls:Array;
		private var _curIndex:int;
		private var _onProgress:Function;
		private var _onComplete:Function;
		
		private var _urlLoader:URLLoader;
		
		public function XmlBatchLoader()
		{
		} 
		
		public function startLoadXmls(urls:Array, onComplete:Function, onProgress:Function=null):void
		{
			_urls = urls;
			_onProgress = onProgress;
			_onComplete = onComplete;
			_curIndex = 0;
			
			if(!_urls || _urls.length==0)
			{
				onBatchLoadComplete();
			}
			continueLoad();
		}
		
		private function onBatchLoadComplete():void
		{
			if(_onComplete != null)
			{
				_onComplete();
			}
		}
		
		private function continueLoad():void
		{
			if(_curIndex >= _urls.length)
			{
				onBatchLoadComplete();
				return;
			}
			
			var url:String = _urls[_curIndex] as String;
			_urlLoader = new URLLoader();
			_urlLoader.dataFormat = URLLoaderDataFormat.TEXT;
			_urlLoader.addEventListener(Event.COMPLETE, onComplete);
			_urlLoader.addEventListener(ProgressEvent.PROGRESS, onProgress);
			_urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			_urlLoader.load(new URLRequest(File.applicationDirectory.resolvePath(url).nativePath));
		}
		
		private function onComplete(e:Event):void
		{
			var url:String = _urls[_curIndex] as String;
			ResourceCache.getInstance().addResourseByUrl(url, new XML(e.target.data));
			_urlLoader.removeEventListener(Event.COMPLETE, onComplete);
			_urlLoader.removeEventListener(ProgressEvent.PROGRESS, onProgress);
			_urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			_urlLoader = null;
			_curIndex++;
			continueLoad();
		}
		
		private function onIOError(e:IOErrorEvent):void
		{
			_urlLoader.removeEventListener(Event.COMPLETE, onComplete);
			_urlLoader.removeEventListener(ProgressEvent.PROGRESS, onProgress);
			_urlLoader.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			_urlLoader = null;
			_curIndex++;
			continueLoad();
		}
		
		private function onProgress(e:ProgressEvent):void
		{
			if(_onProgress != null)
			{
				_onProgress(_curIndex, _urls.length, e.bytesLoaded, e.bytesTotal);
			}
		}
	}
}